package slim3.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import slim3.utils.AccountUtils;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class AccountFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
        // noting to do
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = ((HttpServletRequest) req);

        UserService userService = UserServiceFactory.getUserService();
        String requestUri = request.getRequestURI();

        if (!AccountUtils.isAdmin(request)) {
            ((HttpServletResponse) resp).sendRedirect(userService
                    .createLoginURL(requestUri));
            return;
        }

        chain.doFilter(req, resp);
    }

    public void destroy() {
        // noting to do
    }

}